package com.njzdr.usbcameratest10;

import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.coszero.utilslibrary.file.FileControl;
import com.jiangdg.ausbc.MultiCameraClient;
import com.jiangdg.ausbc.base.CameraFragment;
import com.jiangdg.ausbc.callback.ICaptureCallBack;
import com.jiangdg.ausbc.callback.IEncodeDataCallBack;
import com.jiangdg.ausbc.callback.IPreviewDataCallBack;
import com.jiangdg.ausbc.camera.bean.CameraRequest;
import com.jiangdg.ausbc.render.env.RotateType;
import com.jiangdg.ausbc.widget.AspectRatioTextureView;
import com.jiangdg.ausbc.widget.IAspectRatio;
import com.njzdr.usbcameratest10.databinding.FragmentDemoCameraBinding;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Desc: 实验性功能测试
 * - 视频预览功能,默认需要选中usb摄像头的视频界面
 * - 录像功能,可进行视频录制并存储
 *
 * @author coszero
 * Email:xmqian93@163.com
 * Date:2023/02/17 14:53
 */
public class DemoCameraFragment extends CameraFragment {

    private FragmentDemoCameraBinding binding;

    boolean recode = false;

    public static DemoCameraFragment newInstance() {

        Bundle args = new Bundle();

        DemoCameraFragment fragment = new DemoCameraFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView() {
        super.initView();
        binding.btnRecode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (recode) {
                    recode = false;
                    binding.btnRecode.setText("开始录制");
                    captureStreamStop();
                    FileUtils.releaseFile();
                } else {
                    recode = true;
                    binding.btnRecode.setText("停止录制");
//                    recodeVideoCountDown();
                    recodeVideo();
                }
            }
        });
    }

    @Nullable
    @Override
    protected IAspectRatio getCameraView() {
        return new AspectRatioTextureView(getActivity());
    }

    @Nullable
    @Override
    protected ViewGroup getCameraViewContainer() {
        return binding.flyContent;
    }

    @Nullable
    @Override
    protected View getRootView(@NotNull LayoutInflater layoutInflater, @Nullable ViewGroup viewGroup) {
        binding = FragmentDemoCameraBinding.inflate(layoutInflater, viewGroup, false);
        return binding.getRoot();
    }

    @Nullable
    @Override
    protected UsbDevice getDefaultCamera() {
        List<UsbDevice> deviceList = getDeviceList();
        if (deviceList.size() > 0) {
            UsbDevice usbDevice = deviceList.get(deviceList.size() - 1);
            return usbDevice;
        }
        return super.getDefaultCamera();
    }

    @NotNull
    @Override
    protected CameraRequest getCameraRequest() {
        return new CameraRequest.Builder()
                .setPreviewWidth(640)
                .setPreviewHeight(480)
                .setRenderMode(CameraRequest.RenderMode.OPENGL)
                .setDefaultRotateType(RotateType.ANGLE_0)
                .setAudioSource(CameraRequest.AudioSource.SOURCE_SYS_MIC)
                .setAspectRatioShow(true)
                .setCaptureRawImage(false)
                .setRawPreviewData(false)
                .create();
    }

    @Override
    public void onCameraState(@NotNull MultiCameraClient.ICamera iCamera, @NotNull State state, @Nullable String s) {

    }

    /**
     * 倒计时录制视频
     */
    private void recodeVideoCountDown() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "USBCamera10" + "/videos/";

        FileControl.makeDir(path);

        captureVideoStart(new ICaptureCallBack() {
            @Override
            public void onBegin() {
                Toast.makeText(getActivity(), "开始录制", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(@Nullable String s) {
                Toast.makeText(getActivity(), "录制失败", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onComplete(@Nullable String s) {
                Toast.makeText(getActivity(), "录制结束", Toast.LENGTH_LONG).show();
                recode = false;
                binding.btnRecode.setText("开始录制");
            }
        }, path + System.currentTimeMillis() + ".mp4", 0);
    }

    private void recodeVideo() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-dd-MM HH:mm:ss");
        String path = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "USBCamera10" + "/videos/" + "姓名+编号+" + format.format(new Date()) + ".mp4";
        FileUtils.createfile(path);
        setEncodeDataCallBack(new IEncodeDataCallBack() {
            @Override
            public void onEncodeData(@Nullable byte[] bytes, int i, @NotNull DataType dataType, long l) {
                Log.i("###Preview", "录制视频IE  视频流格式:" + dataType);
                FileUtils.putFileStream(bytes);
            }
        });
        addPreviewDataCallBack(new IPreviewDataCallBack() {
            @Override
            public void onPreviewData(@Nullable byte[] bytes, int i, int i1, @NotNull DataFormat dataFormat) {
                Log.i("###Preview", "录制视频  视频流格式:" + dataFormat);
            }
        });

        captureStreamStart();
    }
}
